﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.IO;

namespace JYStockAnalyser.DataGeter
{
    public partial class FrmZHGeter : Form
    {
        string beginStockNO;
        string endStockNO;
        int beginYear;
        int beginQuarter;
        int endYear;
        int endQuarter;

        WebBrowser webb1;
        HtmlDocument htmldoc1;
        System.Threading.Thread th;

        public FrmZHGeter()
        {
            InitializeComponent();
            m_enterReadyState();
            Control.CheckForIllegalCrossThreadCalls = false;
            webb1 = new WebBrowser();
            webb1.Navigate("about:blank");
            htmldoc1 = webb1.Document.OpenNew(true);
        }

        private void btnGet_Click(object sender, EventArgs e)
        {
            this.btnStop.Enabled = true;
            this.btnGet.Enabled = false;
            this.txtBeginStock.Enabled = false;
            this.txtBeginYear.Enabled = false;
            this.txtBeginQuarter.Enabled = false;
            this.txtEndStock.Enabled = false;
            this.txtEndYear.Enabled = false;
            this.txtEndQuarter.Enabled = false;

            beginStockNO = this.txtBeginStock.Text.Trim();
            endStockNO = this.txtEndStock.Text.Trim();
            try
            {
                beginYear = int.Parse(this.txtBeginYear.Text.Trim());
                beginQuarter = int.Parse(this.txtBeginQuarter.Text.Trim());
                endYear = int.Parse(this.txtEndYear.Text.Trim());
                endQuarter = int.Parse(this.txtEndQuarter.Text.Trim());
            }
            catch (System.FormatException)
            {
                MessageBox.Show("请输入正确的年份和季度");
                return;
            }

            th = new System.Threading.Thread(new System.Threading.ThreadStart(m_getData));
            th.Start();
        }

        private void m_getData()
        {
            List<string> stocks = m_getStocks();

            foreach (string stock in stocks)
            {
                for (int year = beginYear; year <= endYear; year++)
                {
                    for (int quarter = 1; quarter <= 4; quarter++)
                    {
                        if (year == beginYear && quarter < beginQuarter) { continue; }
                        if (year == endYear && quarter > endQuarter) { break; }

                        string strWebContent = m_getWebContent(stock, year, quarter);

                        int start1 = strWebContent.IndexOf("<table width=\"100%\" border=\"0\" cellspacing=1 cellpadding=\"4\">");
                        if (start1 == -1)
                        {
                            if (strWebContent.Contains("该页无法显示"))
                            {
                                quarter -= 1;
                                continue;
                            }

                            System.IO.StreamWriter sw = new StreamWriter(@"log.txt", true);
                            sw.WriteLine("=====================================");
                            sw.WriteLine(stock + "   " + year.ToString() + "   " + quarter.ToString());
                            sw.WriteLine("--------------");
                            sw.WriteLine(strWebContent.ToString());
                            sw.WriteLine("=====================================");
                            sw.Close();
                            continue;
                        }
                        int end1 = strWebContent.IndexOf("</table>", start1 + 100);

                        string content1 = strWebContent.Substring(start1, end1 - start1 + 8);
                        htmldoc1.OpenNew(true);
                        htmldoc1.Write(content1);

                        HtmlElementCollection trs = htmldoc1.GetElementsByTagName("TR");
                        HtmlElementCollection tds1 = trs[1].GetElementsByTagName("TD");
                        HtmlElementCollection tds2 = trs[2].GetElementsByTagName("TD");
                        HtmlElementCollection tds3 = trs[3].GetElementsByTagName("TD");
                        HtmlElementCollection tds4 = trs[4].GetElementsByTagName("TD");
                        HtmlElementCollection tds5 = trs[5].GetElementsByTagName("TD");
                        HtmlElementCollection tds6 = trs[6].GetElementsByTagName("TD");
                        HtmlElementCollection tds7 = trs[7].GetElementsByTagName("TD");
                        HtmlElementCollection tds8 = trs[8].GetElementsByTagName("TD");

                        
                        DataTool.InsertGuideLine(stock, 16001, year, quarter, GetValue(tds1[2].InnerText));        
                        DataTool.InsertGuideLine(stock, 12001, year, quarter, GetValue(tds1[5].InnerText));
                   
                        DataTool.InsertGuideLine(stock, 16002, year, quarter, GetValue(tds2[1].InnerText));  
                        DataTool.InsertGuideLine(stock, 12002, year, quarter, GetValue(tds2[3].InnerText));
                        
                        DataTool.InsertGuideLine(stock, 16003, year, quarter, GetValue(tds3[1].InnerText));
                        DataTool.InsertGuideLine(stock, 13001, year, quarter, GetValue(tds3[4].InnerText));
        
                        DataTool.InsertGuideLine(stock, 16004, year, quarter, GetValue(tds4[1].InnerText));    
                        DataTool.InsertGuideLine(stock, 13002, year, quarter, GetValue(tds4[3].InnerText));
       
                        DataTool.InsertGuideLine(stock, 15001, year, quarter, GetValue(tds5[2].InnerText));    
                        DataTool.InsertGuideLine(stock, 13003, year, quarter, GetValue(tds5[4].InnerText));    
     
                        DataTool.InsertGuideLine(stock, 15002, year, quarter, GetValue(tds6[1].InnerText));    
                        DataTool.InsertGuideLine(stock, 14001, year, quarter, GetValue(tds6[4].InnerText));    

  
                        DataTool.InsertGuideLine(stock, 15003, year, quarter, GetValue(tds7[1].InnerText)); 
                        DataTool.InsertGuideLine(stock, 14002, year, quarter, GetValue(tds7[3].InnerText));    
                   
                        DataTool.InsertGuideLine(stock, 15004, year, quarter, GetValue(tds8[1].InnerText));

                        lbStatus.Items.Add(string.Format("stock : {0} year {1} quarter {2}", stock, year, quarter));
                        lbStatus.SelectedIndex = lbStatus.Items.Count - 1;
       
                    }
                }
            }

            MessageBox.Show("完成!");

            m_enterReadyState();
        }

        private void m_enterReadyState()
        {
            this.btnStop.Enabled = false;
            this.btnGet.Enabled = true;
            this.txtBeginStock.Enabled = true;
            this.txtBeginQuarter.Enabled = true;
            this.txtBeginQuarter.Enabled = true;
            this.txtEndStock.Enabled = true;
            this.txtEndYear.Enabled = true;
            this.txtEndQuarter.Enabled = true;
        }

        private string m_getWebContent(string stock, int year, int quarter)
        {
            string yyyy = year.ToString();
            string mm = string.Empty;
            if (quarter == 1) { mm = "-03-31"; }
            if (quarter == 2) { mm = "-06-30"; }
            if (quarter == 3) { mm = "-09-30"; }
            if (quarter == 4) { mm = "-12-31"; }

            string stockCode = stock;

            ASCIIEncoding encoding = new ASCIIEncoding();
            string postData = "yyyy=" + yyyy;
            postData += ("&mm=" + mm);
            postData += ("&stockCode=" + stockCode);
            byte[] data = encoding.GetBytes(postData);

            HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create("http://www.cninfo.com.cn/gszx/cwzb_gszhnlzb.jsp");

            myRequest.Method = "POST";
            myRequest.ContentType = "application/x-www-form-urlencoded";
            myRequest.ContentLength = data.Length;
            Stream newStream = myRequest.GetRequestStream();

            newStream.Write(data, 0, data.Length);
            newStream.Close();

            HttpWebResponse myResponse = (HttpWebResponse)myRequest.GetResponse();
            StreamReader reader = new StreamReader(myResponse.GetResponseStream(), Encoding.Default);
            string content = reader.ReadToEnd();
            return content;
        }

        private List<string> m_getStocks()
        {
            List<string> stockNOs = new List<string>();
            string[] stocks1 = DataTool.GetAllStocks(beginStockNO, endStockNO, 1);
            string[] stocks2 = DataTool.GetAllStocks(beginStockNO, endStockNO, 2);

            stockNOs.AddRange(stocks1);
            stockNOs.AddRange(stocks2);

            return stockNOs;
        }

        private decimal GetValue(string str)
        {
            decimal v = -77777.77m;
            try
            {
                v = decimal.Parse(str.Trim());
               
            }
            catch(Exception)
            {
            }
            return v;
        }

        private void btnStop_Click(object sender, EventArgs e)
        {
            th.Abort();
        }
    }
}
